<template>
  <div class="table-module">
    <!-- 查询 -->
    <div v-if="tableModule.hadSearch === false ?  false : true" class="query" ref="queryRef">
      <div class="query-content">
        <el-form :model="state.queryForm" style="display: flex;" label-position="left" class="query-form">
          <el-form-item :label="item.label" style="margin-right: 20px; margin-bottom: 0px;"
            v-for="item in tableModule.query" :key="item.prop">
            <el-input v-model="state.queryForm[item.prop]" :placeholder="item.placeholder ? item.placeholder : '请输入'"
              clearable v-if="item.type == 'input'"></el-input>

            <ProjectVerCascader v-else-if="item.type == 'cascader'" :options="options"
              v-model="state.queryForm[item.prop]" />
            <el-select v-model="state.queryForm[item.prop]" clearable
              :placeholder="item.placeholder ? item.placeholder : '请输入'" v-else-if="item.type == 'select'">
              <el-option v-for="cItem in item.options" :key="cItem.key" :label="cItem.label" :value="cItem.value" />
            </el-select>
            <el-select v-model="state.queryForm[item.prop]" clearable
              :placeholder="item.placeholder ? item.placeholder : '请输入'" v-else-if="item.type == 'selectdic'">
              <el-option v-for="cItem in getDicList(item.options)" :key="cItem.dicCode" :label="cItem.dicName"
                :value="cItem.dicCode" />
            </el-select>
            <el-date-picker v-model="state.queryForm[item.prop]" clearable type="daterange"
              :value-format="item.valueFormat || 'yyyy-MM-dd'" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" v-else-if="item.type == 'daterange'" />
          </el-form-item>
        </el-form>
      </div>
      <div class="slot">
        <el-button @click="Search" type="primary" plain>查询</el-button>
        <el-button @click="Recover">重置</el-button>
        <!-- slot插槽（用来添加表格其他操作，比如，新增数据，删除数据等其他操作） -->
        <slot name="event"></slot>
        <!-- 
          动态表头显示，根据表格每条配置项中的show字段来决定改列是否显示或者隐藏
        -->
        <!-- <el-popover placement="bottom" title="表格配置" :width="200" trigger="click">
          <div v-for="(item, index) in tableModule.columns" :key="index">
            <el-checkbox v-model="item.show" :label="item.label" :true-label="1" :false-label="0" />
          </div>
          <template #reference>
            <el-button :icon="Operation"></el-button>
          </template>
        </el-popover> -->
      </div>
    </div>
    <!-- 表格 -->
    <!-- style中是计算表格的高度的 -->
    <el-table :data="dataList" border height="100%" :style="{ 'height': `calc(100vh - ${queryHeight + 156}px)` }"
      v-loading="loading" :row-class-name="tableRowClassName" :cell-class-name="tableCellClassName" id="el-table"
      ref="tableRef">
      <el-table-column v-if="tableModule.hadCheckbox" type="selection" width="50" align="center" />
      <el-table-column v-if="tableModule.hadIndex" align="center" label="序号" type="index" width="80" />
      <!-- columns表格配置数据 -->
      <template v-for="(item, index) in tableModule.columns">
        <!-- 循环 columns 紧接着判断每个字段的类型 -->
        <el-table-column :prop="item.prop" :label="item.label" :align="item.align || 'left'" :width="item.width"
          :min-width="item.min_width" :fixed="item.fixed" v-if="item.show" show-overflow-tooltip>
          <template slot-scope="scope" #default="scope">
            <div v-if="item.type == 'dict'">
              {{ getDicName(scope.row[item.prop], item.options) }}
            </div>
            <!-- image 就是使用 el-image展示我们的图片咯 -->
            <div v-else-if="item.type == 'image'">
              <el-image style="width: 60px; height: 60px" :src="scope.row[item.prop]"
                :preview-src-list="[scope.row[item.prop]]" :preview-teleported="true">
              </el-image>
            </div>
            <!-- formatDate 方法将时间戳格式化为年月日时分秒的格式 -->
            <div v-else-if="item.type == 'time'">{{ formatDate(scope.row[item.prop]) }}</div>
            <!-- 类型都不匹配时直接展示 -->
            <div v-else>{{ scope.row[item.prop] }}</div>
          </template>
        </el-table-column>
      </template>
      <!-- 这里的插槽用于列表的操作列 -->
      <slot name="tableColumn"></slot>
    </el-table>
    <!-- 分页 -->
    <Pagination v-if="tableModule.hadSearch === false ?  false : true" :layout="layout" :pageSizes="pageSizes" :pageable="pages"
      :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange" />
  </div>
</template>

<script setup>
import { onMounted, reactive, toRefs, ref } from 'vue'
import { formatDate, postRequest } from "@/utils/api"
import { ElTable } from 'element-plus';
// import { Operation } from '@element-plus/icons-vue'
import { getDicList, getDicName, transformToTreeData, getVersionData } from "@/utils/dic"

const options = transformToTreeData(getVersionData(), 2)

const props = defineProps({
  tableModule: Object, // 由父组件传递而来
  layout: { // 分页功能配置
    type: String,
    default: "total, sizes, prev, pager, next",
  },
  pageSizes: { // 分页：每页条数配置
    type: Array,
    default() {
      return [10, 20, 30, 50];
    },
  },
})

const queryList = () => {
  state.loading = true
  const param = { ...state.pages, ...state.queryForm }
  delete param.total
  postRequest(props.tableModule.api, param)
    .then(resp => {
      state.loading = false
      state.dataList = resp.data.data.records
      if(props.isPage) {
        state.pages.total = resp.data.data.total
        state.pages.pageNum = resp.data.data.current
        state.pages.pageSize = resp.data.data.size
      }
    })
    .catch(e => {
      state.loading = false
      alert(e)
    })
}
const state = reactive({
  rowIndex: 0, // 行索引 用于可编辑单元格
  columnIndex: 0, // 列索引 用于可编辑单元格
  queryHeight: 0,
  queryForm: {}, // 查询form表单
  loading: false, // 加载状态
  dataList: [], // 列表数据
  pages: { // 分页数据
    pageNum: 1,
    pageSize: 10,
    total: 0
  }
})

const {
  queryHeight, loading, dataList, pages
} = toRefs(state)

const queryRef = ref(null);

onMounted(() => {
  // 这里拿到query模块的高度，适配页面高度的
  if(props.tableModule.hadSearch !== false) {
    setTimeout(() => {
      state.queryHeight = queryRef.value.clientHeight
    }, 100);
  }

  // 为每个表格配置项添加show属性，默认1为显示状态
  props.tableModule.columns?.forEach(item => {
    item.show = 1
  })
  queryList()
})

// 为所有单元格设置一个固定的 className
function tableCellClassName({ column, columnIndex }) {
  column.Indexs = columnIndex;
}

// 每页条数改变
const handleSizeChange = (val) => {
  state.pages.pageNum = 1;
  state.pages.pageSize = val;
  queryList()
};

// 当前页改变
const handleCurrentChange = (val) => {
  state.pages.pageNum = val;
  queryList()
};

// 点击查询按钮时触发
function Search() {
  state.pages.pageNum = 1
  queryList()
}

// 点击重制触发
function Recover() {
  state.queryForm = {}
  queryList()
}

defineExpose({ queryList })
</script>

<style scoped lang="scss">
.table-module {
  .query {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    margin-bottom: 10px;

    .query-content {
      display: flex;
      align-items: flex-start;

      .query-form {
        .el-form-item {
          margin: 0px;
          margin-right: 20px;
        }

        .el- {
          width: 200px;
        }

        ::v-deep(.el-select) {
          .el- {
            width: 200px;
          }
        }
      }
    }

    .slot {
      display: flex;
      justify-content: flex-end;
      padding-right: 48px;
    }
  }
}
</style>
